<template>
  <div class="draggableConfig">
    <a-spin :spinning="loading">
      <component
        :is="configFormComponent"
        :rowData="rowData"
        :elements="elements"
        :draggableEl="draggableEl"
        @getConfig="getConfig"
        ref="configFormRef"
      />
    </a-spin>
  </div>
</template>
<script setup>
import BIAN_YA_QI from "./configForm/BIAN_YA_QI.vue";
import DIAN_CHI_CU from "./configForm/DIAN_CHI_CU.vue";
import DIAN_CHI_DUI from "./configForm/DIAN_CHI_DUI.vue";
import BING_WANG_GUI from "./configForm/BING_WANG_GUI.vue";
import HUAN_WANG_GUI from "./configForm/HUAN_WANG_GUI.vue";
import CHONG_DIAN_ZHUANG from "./configForm/CHONG_DIAN_ZHUANG.vue";
import LINE from "./configForm/LINE.vue";
import JI_LIANG_DIAN_BIAO from "./configForm/JI_LIANG_DIAN_BIAO.vue";
import JI_ZHUANG_XIANG from "./configForm/JI_ZHUANG_XIANG.vue";
import GUAN_KOU_BIAO from "./configForm/GUAN_KOU_BIAO.vue";
import {
  EQUIP_TYPE,
  EQUIP_API,
  EQUIP_DETAILS_API,
} from "@/constants/stationConfig";
import { useStionConfigStore } from "@/stores/stationConfig";

const props = defineProps({
  rowData: {
    type: Object,
  },
  addStationId: {
    type: String,
  },
  elements: {
    type: Array,
  },
  draggableEl: {
    type: Array,
  },
});
const $api = inject("$api");
const {
  stionConfigState,
  changeConfigData,
  changeEquipType,
  changeConfigDataSaveLoading,
  changeIsEditDrag,
} = useStionConfigStore();
const equipType = computed(() => stionConfigState.equipType); // 当前选择的器部件
const systemId = computed(() => stionConfigState.dragData.systemId); // 当前选择的器部件
const emits = defineEmits(["handleSaveConfig"]);
const loading = ref(false);
const configFormComponent = ref(null);
const configFormRef = ref(null);
const isChargeProject = computed(() => props.rowData.isChargeProject);
const isContainerProject = computed(() => props.rowData.isContainer);
watch(
  () => equipType.value,
  async (val) => {
    if (!val && val !== 0) {
      configFormComponent.value = null;
      return;
    }
    switch (val) {
      case EQUIP_TYPE.BIAN_YA_QI:
        configFormComponent.value = BIAN_YA_QI;
        break;
      case EQUIP_TYPE.DIAN_CHI_CU:
        configFormComponent.value = DIAN_CHI_CU;
        break;
      case EQUIP_TYPE.DIAN_CHI_DUI:
        configFormComponent.value = DIAN_CHI_DUI;
        break;
      case EQUIP_TYPE.BING_WANG_GUI:
        configFormComponent.value = BING_WANG_GUI;
        break;
      case EQUIP_TYPE.HUAN_WANG_GUI:
        configFormComponent.value = HUAN_WANG_GUI;
        break;
      case EQUIP_TYPE.CHONG_DIAN_ZHUANG:
        configFormComponent.value = CHONG_DIAN_ZHUANG;
        break;
      case EQUIP_TYPE.GUAN_KOU_BIAO:
        configFormComponent.value = GUAN_KOU_BIAO;
        break;
      case EQUIP_TYPE.JI_ZHUANG_XIANG:
        configFormComponent.value = JI_ZHUANG_XIANG;
        break;
      case EQUIP_TYPE.LINE:
        configFormComponent.value = LINE;
        break;
      case EQUIP_TYPE.COMMON:
      case EQUIP_TYPE.FU_ZAI:
        configFormComponent.value = null;
        break;
      default:
        // 有值，但没有定义的，默认是通用计量电表
        configFormComponent.value = JI_LIANG_DIAN_BIAO;
        break;
    }
  },
  { immediate: true }
);
watch(
  () => systemId,
  async (val) => {
    if (!val.value) {
      // 如果点击了别的器部件，还没保存的，需要清空配置，获取资产编码
      const arr = [
        EQUIP_TYPE.COMMON,
        EQUIP_TYPE.GUAN_KOU_BIAO,
        EQUIP_TYPE.BING_WANG_BIAO,
        EQUIP_TYPE.LINE,
      ];
      if (arr.includes(stionConfigState.equipType)) {
        return;
      }
      let res;
      let assetCode;
      if (stionConfigState.equipType === EQUIP_TYPE.CHONG_DIAN_ZHUANG) {
        const promises = [
          $api.assertCode({ type: EQUIP_TYPE.DIAN_CHI_DUI }),
          $api.assertCode({ type: EQUIP_TYPE.DIAN_CHI_CU }),
        ];
        res = await Promise.all(promises);
        assetCode = res.map((item) => item.data);
      } else {
        res = await $api.assertCode({
          type: stionConfigState.equipType,
        });
        assetCode = res.data;
      }
      changeConfigData({
        assetCode,
      });
      return;
    }
    const apiName =
      EQUIP_DETAILS_API[stionConfigState.equipType] ||
      "stationDeviceComponentDetails";
    loading.value = true;
    const res = await $api[apiName](val.value);
    loading.value = false;
    // 如果是储充项目，systemId拿energyId, 如果是集装箱项目，取containerId, 普通项目拿deviceId
    let systemId = null;
    if (isContainerProject.value) {
      systemId = res.data.containerId;
    } else if (isChargeProject.value) {
      systemId = res.data.energyId;
    } else if (stionConfigState.equipType === EQUIP_TYPE.GUAN_KOU_BIAO) {
      systemId = res.data.id;
    } else {
      systemId = res.data.deviceId;
    }
    if (res.code === 0) {
      const configData = {
        ...res.data,
        systemId,
      };
      changeConfigData(configData);
      changeIsEditDrag(true);
    }
  },
  { deep: true }
);
const filterElements = (elements) => {
  // 过滤掉没有 systemId 的
  const result = [];
  elements.forEach((item) => {
    let filteredChildren = [];
    if (item.systemId || item.isChildEquip || item.type === EQUIP_TYPE.FU_ZAI) {
      filteredChildren = item.children ? filterElements(item.children) : [];
      result.push({
        ...item,
        children: filteredChildren,
      });
    } else if (item.children) {
      filteredChildren = filterElements(item.children);
      if (filteredChildren.length > 0) {
        result.push({
          ...item,
          children: filteredChildren,
        });
      }
    }
  });
  return result;
};

const getConfig = async (data) => {
  const { dragData, equipData } = stionConfigState;
  let params = {
    ...data.value,
    stationId: props.rowData.stationId || props.addStationId, // 带上当前的电站id
    modelId: equipData.id, // 带上器部件id
    modelType: equipData.modelType, // 带上器部件类型
  };
  if (data.value.type === EQUIP_TYPE.LINE) {
    const configData = {
      ...data.value,
    };
    changeConfigData({
      ...configData,
      isEdit: false,
    }); // 保存配置数据
    changeIsEditDrag(true);
    await nextTick();
    emits("handleSaveConfig");
    return;
  }
  changeConfigDataSaveLoading(true);

  let containerId = null; // 用于集装箱项目，存储返回的containerId
  
  if (dragData.systemId) {
    // 有 systemId ，则是编辑
    params.id = dragData.systemId; // 编辑带上器部件id
    const apiName = EQUIP_API[dragData.type] || "stationDeviceComponent";
    const res = await $api[apiName](params, "put");
    if (res.code === 0) {
      containerId = res.data; // 获取返回的containerId
      const configData = {
        ...data.value,
        systemId: dragData.systemId, // 修复：确保在编辑模式下保留systemId
      };
      changeConfigData({
        ...configData,
        isEdit: false,
      }); // 保存配置数据
      changeIsEditDrag(true);
      
      // 如果不是集装箱项目，直接触发handleSaveConfig
      if (data.value.type !== EQUIP_TYPE.JI_ZHUANG_XIANG) {
        await nextTick();
        emits("handleSaveConfig");
        message.success("保存配置成功");
      }
    }
  } else {
    // 没有 systemId，则是新增
    const apiName = EQUIP_API[dragData.type] || "stationDeviceComponent";
    const res = await $api[apiName](params, "post");
    if (res && res.code === 0) {
      containerId = res.data; // 获取返回的containerId
      const configData = {
        ...data.value,
        systemId: res.data, // 将接口返回的器部件id保存起来，作为配置的systemId
      };
      changeConfigData({
        ...configData,
        isEdit: false,
      }); // 保存配置数据
      changeIsEditDrag(true);
      
      // 如果不是集装箱项目，直接触发handleSaveConfig
      if (data.value.type !== EQUIP_TYPE.JI_ZHUANG_XIANG) {
        await nextTick();
        emits("handleSaveConfig");
        message.success("保存配置成功");
      }
    }
  }
  // 集装箱项目特殊处理：获取blockIds并保存到configData中，然后触发handleSaveConfig更新elements
  if (data.value.type === EQUIP_TYPE.JI_ZHUANG_XIANG && containerId) {
    try {
      const containerRes = await $api.containerRelation(containerId);
      if (containerRes.code === 0 && containerRes?.data?.blockIds) {
        // 将blockIds保存到configData中，让handleSaveDragConfig处理电池簇的创建和更新
        const updatedConfigData = {
          ...stionConfigState.configData,
          children: {
            ...stionConfigState.configData.children,
            blockIds: containerRes.data.blockIds
          }
        };
        changeConfigData(updatedConfigData);        
        // 在获取blockIds后触发handleSaveConfig，这样handleSaveDragConfig可以使用blockIds
        await nextTick();
        emits("handleSaveConfig");
        message.success("保存配置成功");
      }
    } catch (error) {
      // 即使获取blockIds失败，也要触发handleSaveConfig保存基本配置
      await nextTick();
      emits("handleSaveConfig");
      message.success("保存配置成功");
    }
  }
  
  changeConfigDataSaveLoading(false);
  
  // 配置保存后，再保存拓扑图。防止配置信息和拓扑图上渲染的信息不一致
  // 保存拓扑图时，需要过滤掉应该有 systemId 但是没有的数据
  const elements = filterElements(props.elements);
  const topologyMapParams = {
    stationId: props.rowData.stationId || props.addStationId,
    frontData: JSON.stringify({
      data: elements,
    }),
  };
  await $api.stationTopologyMapSave(topologyMapParams, "post");
};
onUnmounted(() => {
  configFormComponent.value = null;
  changeEquipType("");
});
</script>
<style lang="less" scoped>
.draggableConfig {
  ::v-deep(.ant-form-item-explain-error) {
    text-align: left;
    padding-left: 5px;
  }
}
.formInput {
  width: 155px;
}
</style>